package hk.ust.android_competition.event;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * Created by Silver on 6/1/15.
 */
public class MiniGame {
    private ArrayList<Character> characterList;
    private ArrayList<Integer> shuffledList = new ArrayList<>();
    private boolean isDraw = false;
    private final int[][] winTable = new int[][]{{0, 1, 2}, {0, 4, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {2, 4, 6}, {3, 4, 5}, {6, 7, 8}};
    private final char playerChar = 'p';
    private final char computerChar = 'c';
    private final char space = '*';
    private boolean isPlayerWin = false;
    private boolean isComputerWin = false;
    private int turn = 0;

    public boolean isEnd() {
        return (isDraw || isComputerWin || isPlayerWin);
    }

    public boolean isPlayerWin() {
        return isPlayerWin;
    }

    public MiniGame() {
        characterList = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            characterList.add(space);
            shuffledList.add(i);
        }
    }

    public boolean isPlayerChose(int index) {

        return (characterList.get(index) == playerChar);
    }

    public boolean isComputerChose(int index) {
        return (characterList.get(index) == computerChar);
    }

    public void playerMove(int index) {
        if (characterList.get(index) == '*' && !isEnd()) {
            characterList.set(index, playerChar);
            turn++;
            if (turn > 5)
                checkWin();
            if (!isEnd()) {
                Collections.shuffle(shuffledList);
                for (int i = 0; i < shuffledList.size(); i++) {
                    if (characterList.get(shuffledList.get(i)) == '*') {
                        computerMove(shuffledList.get(i));
                        break;
                    }
                }
            }
        }
    }

    public void computerMove(int index) {
        characterList.set(index, computerChar);
        turn++;
        if (turn > 5)
            checkWin();
    }

    public boolean isComputerWin() {
        return isComputerWin;
    }

    private void checkWin() {
        boolean won = false;
        won = checkGameWin(playerChar);
        if (won) {
            isPlayerWin = true;
            return;
        }
        won = checkGameWin(computerChar);
        if (won) {
            isComputerWin = true;
        }
        if (turn == 9) {
            isDraw = true;
        }
    }

    private boolean checkGameWin(char symbol) {
        boolean won = false;
        for (int i = 0; i < winTable.length; i++) {
            won = true;
            for (int j = 0; j < winTable[0].length; j++) {
                won = won && (characterList.get(winTable[i][j]) == symbol);
            }
            if (won)
                break;
        }
        return won;
    }

}
